package rmi.client;

import java.rmi.RemoteException;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import rmi.OrderItem;
import rmi.PolicyFileLocator;
import rmi.Product;
import rmi.WareHouse;

public class Client {

    public static final String CONTEXT_NAME = "java.naming.factory.initial";
    public static final String IIOP_STRING = "com.sun.jndi.cosnaming.CNCtxFactory";
    public static final String URL_NAME = "java.naming.provider.url";

    private String clientName;
    private int orderNr;
    private Context context;

    public Client(String someName, String serverAddressPort) {
        clientName = someName;

        System.setProperty("java.security.policy", PolicyFileLocator.getLocationOfPolicyFile(false));

        Properties iiopProperties = new Properties();
        iiopProperties.put(CONTEXT_NAME, IIOP_STRING);
        iiopProperties.put(URL_NAME, "iiop://" + serverAddressPort);

        try {
            context = new InitialContext(iiopProperties);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public List<Product> getProductList() {
        WareHouse w = null;
        List<Product> productList = null;

        try {
            w = (WareHouse) context.lookup("warehouse");
            productList = w.getProductsList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return productList;
    }

    public WareHouse getWareHouse() {
        WareHouse w = null;

        try {
            w = (WareHouse) context.lookup("warehouse");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return w;
    }

    public void addNewOrder() {
        try {
            orderNr = getWareHouse().addNewOrder(clientName);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public boolean addConfirmation() {
        boolean succes = false;
        try {
            succes = getWareHouse().confirmOrder(clientName, orderNr);

        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return succes;
    }

    public boolean addOrderItem(int amount, int selectedIndex) {
        boolean succes = false;
        OrderItem oi = new OrderItem(clientName, orderNr, selectedIndex, amount);
        try {
            succes = getWareHouse().addOrderItem(oi);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return succes;
    }

    public String getOrderSummary() {
        String summary = null;
        try {
            summary = getWareHouse().getOrderSummary(clientName, orderNr);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return summary;
    }
}
